<?php

namespace app\job;

use app\api\service\GongzonghaoService;
use think\Env;
use think\queue\Job;

/**
 * 消费者类
 * 用于处理队列中的任务
 */
class Qrcode
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        //有效消息到达消费者时可能已经不再需要执行了
        if(!$this->checkJob($data)){
            $job->delete();
            return;
        }

        //执行业务处理
        if($this->doJob($data)){
            $job->delete();//任务执行成功后删除
        }else{
            $job->delete();
        }
    }

    /**
     * 消息在到达消费者时可能已经不需要执行了
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean 任务执行的结果
     */
    private function checkJob($data)
    {
        //验证数据
//        $id = $data["id"];
        if(isset($data['id'])){
            return true;
        }else{
            var_dump('参数有误！');
            return true;
        }
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     */
    private function doJob($data)
    {
        //推广码
        $user_id = $data['id'];
        //生成一张推广海报
        $gongzonService = new GongzonghaoService();
        $save_qrcode_image = ROOT_PATH . "public/storage/qrcode/qrcode_{$user_id}.jpg";
        $newImagePath     = ROOT_PATH . "public/storage/qrcode/qrcode_haibao_{$user_id}.png";
        $backgroundUrl = getConfByType('basic')['tuiguang_haibao'];
        $backgroundUrl = str_replace(request()->domain(),'',$backgroundUrl);// /storage/local/20240410/c15c47169bb7ab94d71ea0bcfbe3b174.png
        $backgroundPath = ROOT_PATH ."public".$backgroundUrl;
        // pages/index/index?share_code=125554sdas54

        $domain =  Env::get('app.HOST_URL', '');
        try {
            $weixinToken = $gongzonService->get_weixin_token();
            if($weixinToken['code'] == 0){
                $qrcode_info = $gongzonService->getQrcodeByWechat($weixinToken['data']['weixin_access_token'],$user_id,$save_qrcode_image);
                if($qrcode_info['code'] == 0){
                    //合成背景图
                    $qrcode_url = $qrcode_info['data']['qrcode_url'];
                    $qrcode_path = $qrcode_info['data']['qrcode_path'];
                    $gongzonService->mergeImage($backgroundPath,$qrcode_path,$newImagePath);

                    $haibao_url = str_replace(ROOT_PATH . "public",$domain,$newImagePath);
                    pp($haibao_url);
                    db('user')->where('id',$user_id)->update(['qrcode'=>$haibao_url]);
                }
            }
        }catch (\Exception $e){

        }

        return true;
    }

    // 消息队列执行失败后会自动执行该方法
    public function failed($data)
    {
        ppd('消息队列达到最大重复执行次数后失败：' . json_encode($data));
    }
}
